<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Tools class
 */
class Tools {
	/**
	 * Redirect
	 */
	public static function redirect($url) {
		if (!headers_sent()) {
			//@header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
			@header('Location: ' . $url);
		} else {
			echo '<script type="text/javascript">';
			echo 'location.replace("' . $url . '");';
			echo '</script>';
			echo '<noscript>';
			echo '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
			echo '</noscript>';
		}
		exit;
	}
	
	public static function secondsToTimeString($seconds) {
		$result = '';
		if ($seconds > 0) {
			$result = '+';
		} else if ($seconds < 0) {
			$result = '-';
		} else {
			$result = '';
		}
		$seconds = abs($seconds);
		$hours = self::fixZeros(intval($seconds / 3600), 2);
		$minutes = self::fixZeros(intval(($seconds % 3600) / 60), 2);
		$result .= $hours . ':' . $minutes;
		
		return $result;
	}

	public static function fixZeros($num, $minlen = 0) {
		$result = strval($num);
		while (strlen($result) < $minlen) {
			$result = '0' . $result;
		}
		return $result;
	}

	public static function utcTime($timestamp = 0, $offset = 0, $dst = 0) {
		if (!$timestamp) { $timestamp = time(); }

		$offset += $dst;
		$timestamp += $offset;

		return $timestamp;
	}


	public static function bitCheck($value, $n) {
		$result = false;
		
		$value = (int) $value;
		if ($value & (1 << ($n - 1))) {
			$result = true;
		}
		
		return $result;
	}

	public static function bitSet($value, $n) {
		$value = (int) $value;
		$value = ($value | (1 << ($n - 1)));

		return $value;
	}

	public static function bitClear($value, $n) {
		$value = (int) $value;
		$value = (0 & (1 << ($n - 1)));
		return $value;
	}

	public static function bitSwitch($value, $n) {
		// TODO: Implement toolsSwitchBit
		return $value;
	}

	/**
	 * Factory value
	 */
	public static function parse($str, $vars = array(), $start_tag = '{%', $end_tag = '%}') {
		if (!empty($vars)) {
			foreach ($vars as $key => $val) {
				$var_str = $start_tag . $key . $end_tag;
				$str = str_replace($var_str, $val, $str);
			}
		}
		return $str;
	}

}
